import { Component, forwardRef, Input, ChangeDetectionStrategy, Injector } from '@angular/core'
import { NG_VALUE_ACCESSOR } from '@angular/forms'
import { Observable } from 'rxjs'
import { IMCC, IMCCQuery, MCCType } from './mcc-select.interface'
import { MccService } from './mcc.service'
import { AbstractCustomSelectComponent } from '../custom-select/custom-select.component'
import { IGenericPagination } from '@shared/interfaces/pagination'
import { objectArrayDeduplication } from 'app/utils/helpers'

@Component({
  selector: 'app-mcc-select',
  templateUrl: './mcc-select.component.html',
  styles: [],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => MccSelectComponent),
      multi: true,
    },
  ],
})
export class MccSelectComponent extends AbstractCustomSelectComponent<IMCC, IMCCQuery> {
  constructor(private mccService: MccService, public injector: Injector) {
    super(injector)
  }

  @Input() mccType: MCCType

  _params: IMCCQuery = {
    paymentBrand: this.mccType,
    limit: 10,
    page: 1,
    keyword: '',
  }

  deduplicate(list: IMCC[]): IMCC[] {
    return objectArrayDeduplication(list, 'mccCode')
  }

  compareFn = (o1: IMCC, o2: IMCC) => {
    return o1 && o2 ? o1.mccCode === o2.mccCode : o1 === o2
  }

  query(params: IMCCQuery): Observable<IGenericPagination<IMCC>> {
    return this.mccService.getList(params)
  }

  getParams(): IMCCQuery {
    return this._params
  }

  loadMore(): void {
    if (this.isLoading) {
      return
    }
    this.isLoading = true
    this._params.page++
    this.searchChange$.next(this.getParams())
  }

  onSearch(value: string): void {
    this.isLoading = true
    this._options = []
    this._params.page = 1
    this._params.keyword = value
    this.searchChange$.next(this.getParams())
  }
}
